package com.meiyu.live.ui.mine;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.UserInfoUpdateEvent;
import com.meiyu.live.net.FileReqPackage;
import com.meiyu.live.net.UploadFile;
import com.meiyu.live.net.callback.UploadCallBack;
import com.meiyu.live.net.param.UploadFileParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.UploadResponse;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.util.BitmapUtil;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.io.File;

import de.greenrobot.event.EventBus;

/**
 * Created by zbl on 2016/8/28.
 * 个人信息修改界面
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_IMAGE = 1;
    private static final int REQUEST_CODE_BIND = 2;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    protected NetLoadingDailog dialog_loading;

    private View btn_back, btn_post, ll_phone_status;
    private ImageView iv_avatar;
    private EditText et_nickname, et_hometown, et_signature;
    private AppCompatRadioButton[] rb_sex;
    private TextView tv_phone_status;

    private static final String[] SEX_STRING = {"f", "m", ""};

    private String url_avatar, path_avatar;

    private boolean isDoing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        init();
    }

    private void init() {
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        dialog_loading = new NetLoadingDailog(this);

        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_post = findViewById(R.id.btn_post);
        btn_post.setOnClickListener(this);
        tv_phone_status = (TextView) findViewById(R.id.tv_phone_status);
        ll_phone_status = findViewById(R.id.ll_phone_status);
        ll_phone_status.setOnClickListener(this);

        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        iv_avatar.setOnClickListener(this);
        et_nickname = (EditText) findViewById(R.id.et_nickname);
        et_hometown = (EditText) findViewById(R.id.et_hometown);
        et_signature = (EditText) findViewById(R.id.et_signature);

        rb_sex = new AppCompatRadioButton[]{
                (AppCompatRadioButton) findViewById(R.id.rb_sex_female),
                (AppCompatRadioButton) findViewById(R.id.rb_sex_male),
                (AppCompatRadioButton) findViewById(R.id.rb_sex_secret)
        };
        rb_sex[2].setChecked(true);

        updateUserInfo();
    }

    private void updateUserInfo() {
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            url_avatar = personalInfo.getAvatar();
            imageLoader.displayImage(url_avatar, iv_avatar, options);
            et_nickname.setText(personalInfo.getName());
            et_hometown.setText(personalInfo.getAddress());
            et_signature.setText(personalInfo.getSignature());
            if (personalInfo.getMobile_auth() == 1) {
                ll_phone_status.setVisibility(View.GONE);
            } else {
                ll_phone_status.setVisibility(View.VISIBLE);
            }
            for (int i = 0; i < SEX_STRING.length; i++) {
                if (SEX_STRING[i].equals(personalInfo.getSex())) {
                    rb_sex[i].setChecked(true);
                    break;
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            finish();
        } else if (view == ll_phone_status) {
            Intent intent = new Intent(this, bindPhoneActivity.class);
            startActivityForResult(intent, REQUEST_CODE_BIND);
        } else if (view == btn_post) {
            String name = et_nickname.getText().toString();
            if (TextUtils.isEmpty(name)) {
                ToastUtil.show("用户名不能为空");
                return;
            }
            dialog_loading.loading();
            uploadAvatar();
        } else if (view == iv_avatar) {
            if (isDoing) {
                return;
            }
//            Intent intent = new Intent();
//            intent.setType("image/*");
//            intent.setAction(Intent.ACTION_GET_CONTENT);
//            startActivityForResult(intent, REQUEST_CODE_IMAGE);

            Intent pickintent = new Intent(Intent.ACTION_PICK, null);
            /**
             * 下面这句话，与其它方式写是一样的效果，如果：
             * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             * intent.setType(""image/*");设置数据类型
             * 如果要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
             */
            pickintent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(pickintent, REQUEST_CODE_IMAGE);
            isDoing = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isDoing = false;
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            if (data != null) {
                //取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
                Uri imageUri = data.getData();
                //返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
                if (imageUri != null) {

                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(imageUri, proj, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (cursor.moveToFirst()) {
                        path_avatar = cursor.getString(column_index);
                        imageLoader.displayImage(imageUri.toString(), iv_avatar, options);
                    }
                }

            }
        } else if (requestCode == REQUEST_CODE_BIND && resultCode == RESULT_OK) {
            ll_phone_status.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        dialog_loading.dismissDialog();
        super.onError();
    }

    private void uploadAvatar() {
        if (TextUtils.isEmpty(path_avatar)) {
            postData();
        } else {
            //文件上传
            //("video_pic"代表切片；"avatar"代表头像)
            String body = new FileReqPackage(new UploadFileParams("avatar")).packetParam();
            new Thread(new UploadFile(Constant.URL + Constant.UrlParams.UPLOAD, BitmapUtil.compressImage(path_avatar), new File(path_avatar).getName(), body, new UploadCallBack() {
                @Override
                public void response(final UploadResponse response) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (response == null || response.getHash() == null || TextUtils.isEmpty(response.getHash().getAvatar_url())) {
                                ToastUtil.show("上传头像失败");
                                dialog_loading.dismissDialog();
                            } else {
                                url_avatar = response.getHash().getAvatar_url();
                                postData();
                            }
                        }
                    });
                }
            })).start();
        }
    }

    private void postData() {
        String sex = "";
        for (int i = 0; i < rb_sex.length; i++) {
            if (rb_sex[i].isChecked()) {
                sex = SEX_STRING[i];
                break;
            }
        }
        String hometown = et_hometown.getText().toString();
        if (hometown.equals("请选择省市")) {
            hometown = "";
        }
        request(new PersonalInfo(
                UserConfig.getInstance().getUserId(),
                et_nickname.getText().toString(),
                sex,
                et_signature.getText().toString(),
                url_avatar,
                hometown), BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {
                dialog_loading.dismissDialog();
                EventBus.getDefault().post(new UserInfoUpdateEvent());
                finish();
            }
        });
    }
}
